package com.jeecms.wicool.manager.cms.impl;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeecms.cms.entity.main.CmsUser;
import com.jeecms.common.hibernate3.Updater;
import com.jeecms.common.page.Pagination;
import com.jeecms.wicool.dao.cms.CmsVoteDao;
import com.jeecms.wicool.entity.cms.CmsVote;
import com.jeecms.wicool.entity.shops.ShopInfo;
import com.jeecms.wicool.manager.cms.CmsVoteMng;
import com.jeecms.wicool.manager.shops.WiShopInfoMng;

@Service
@Transactional
public class CmsVoteMngImpl implements CmsVoteMng {
	
	private CmsVoteDao dao;
	@Autowired
	public void setDao(CmsVoteDao dao) {
		this.dao = dao;
	}
	
	@Transactional(readOnly = true)
	public Pagination getPage(String title,int pageNo, int pageSize,CmsUser user) {
		Pagination page = dao.getPage(title, pageNo, pageSize, user);
		return page;
	}
	@Override
	public CmsVote findById(Integer id) {
		CmsVote entity = dao.findById(id);
		return entity;
	}
	@Override
	public CmsVote update(CmsVote bean,Integer shopId) {
		ShopInfo shop= shopMng.findById(shopId);
		bean.setShop(shop);
		Updater<CmsVote> updater = new Updater<CmsVote>(bean);
		bean = dao.updateByUpdater(updater);
		return bean;
	}
	
	@Override
	public CmsVote save(CmsVote bean,Integer shopId) {
		
		ShopInfo shop= shopMng.findById(shopId);
		bean.setShop(shop);
		boolean isHave=dao.isHave(bean);
		if(isHave){
			CmsVote c = dao.findByCmsVote(bean);
			bean.setId(c.getId());
			bean.setCreateTime(c.getCreateTime());
			SimpleDateFormat simpleTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dateTime = simpleTime.format(new Date());
			Timestamp t = Timestamp.valueOf(dateTime);
			bean.setUpdateTime(t);
			this.update(bean, bean.getShop().getId());
		}else{
		dao.save(bean);
		}
		return bean;
	}

	@Override
	public CmsVote deleteById(Integer id) {
		CmsVote bean = dao.deleteById(id);
		return bean;
	}
	@Override
	public CmsVote[] deleteByIds(Integer[] ids) {
		CmsVote[] beans = new CmsVote[ids.length];
		for (int i = 0,len = ids.length; i < len; i++) {
			beans[i] = deleteById(ids[i]);
		}
		return beans;
	}
	@Override
	public List<CmsVote> getAll(CmsUser user) {
		// TODO Auto-generated method stub
		return dao.getAll(user);
	}
	@Override
	public CmsVote findByContentId(Integer contentId) {
		// TODO Auto-generated method stub
		return dao.findByContentId(contentId);
	}
	@Autowired
	private WiShopInfoMng shopMng;
	
	
}